package tinynio;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class SelectGroup implements Closeable {

	private Select[] children;
	private static int DEFAULT_THREAD_NUM = Runtime.getRuntime().availableProcessors() * 2;
	private final AtomicInteger childIndex = new AtomicInteger();

	public SelectGroup() throws IOException {
		this(DEFAULT_THREAD_NUM);
	}

	public SelectGroup(int threads) throws IOException {
		if (threads <= 0)
			throw new IllegalArgumentException("threads can not be less than zore!");

		children = new Select[threads];

		for (int i = 0; i < threads; i++)
			children[i] = new Select(this);
	}

	public Select next() {
		return children[Math.abs(childIndex.getAndIncrement() % children.length)];
	}

	@Override
	public void close() throws IOException {
		for (Select select : children) {
			if (select != null)
				select.close();
		}

	}
}
